/*
 * FileHashtable.java
 * 
 * last update: 14.01.2010 by Stefan Saru
 * 
 * author:	Felix(felix@ulise.cs.pub.ro)
 *
 * Obs: N/A
 */

package ide;

import java.io.*;
import java.util.*;


class FileHashtable {

	public static String prefsFileName = System.getProperty("user.home") + File.separatorChar + "vIDE.rc";
	boolean isValid = false;
	Hashtable hash;

	public Object get(String key) {
		Object toDeliver = hash.get(key);

		if (toDeliver == null) System.out.println("Bug : Preferences object does not contain this key: " + key);
		return toDeliver;
	}

	public void put(String key, Object object) {
		hash.put(key, object);
	}


	public void print() {
		String key = new String("cucu");
		System.out.println("Prefs file content enumeration (key, value) : ");

		for (Enumeration e = hash.keys() ; e.hasMoreElements() ;) {
			key = (String)e.nextElement();
			System.out.print(key + "  ==  ");
			try { System.out.println(hash.get(key).toString()); }
			catch (Exception ex) { System.out.println("[not a String]");
			}
		}

		System.out.println("(enumeration end.)");
		System.out.println();
	}


	public void save() {
		try {
			FileOutputStream fostream = new FileOutputStream(prefsFileName);
			ObjectOutputStream oostream = new ObjectOutputStream(fostream);
			oostream.writeObject("vIDE prefs");        //signature

			oostream.writeObject(hash);

			oostream.flush();
			fostream.close();
		} catch (Exception e) {
			System.out.println("IOException saving preferences:\n" + e);
		}

	}

	public FileHashtable() {


		FileInputStream fistream; 
		try {
			ObjectInputStream oistream = new ObjectInputStream(fistream = new FileInputStream(new File(prefsFileName)));

			if (!(((String) oistream.readObject()).equals("vIDE prefs"))) {
				System.out.println("Could not load preferences.\nBad signature.");
				isValid = false;
				return;
			}


			//todo -> check if it's the right version
			hash = (Hashtable) oistream.readObject(); 

			//cam atat?
			fistream.close();
			isValid = true;

		} catch (Exception e) {
			System.out.println("IOException reading preferences:\n" + e);
		}

		if(!isValid) hash = new Hashtable();
	}
}
